//
//  AppDelegate.m
//  LianShangBao
//
//  Created by 主事丫环HU on 2020/8/27.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "AppDelegate.h"
#import "CodeLoginController.h"
#import "JSHAREService.h" //分享
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
@interface AppDelegate ()<WXApiDelegate>
// 微信  AppID：wx38793707308969c8 AppSecret: d4fdb996606263a7e12d67c615b9b7f6
// 支付宝 appID = 2019032163612874
@property (nonatomic, strong) UIView *backGroundView;// 提示更新的弹框
@property (nonatomic, strong) NSString *iosUrl;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //分享设置
    [self jShareConfig];
    //微信
    [WXApi registerApp:@"wx38793707308969c8"];
    //主界面创建
    [self setupRootWindow];
    [self requestVersionNumber];
    return YES;
}
- (void)requestVersionNumber{
 
    [NetWorkTool POST:updateApp param:nil success:^(id dic) {
        KMyLog(@"返回的数据是 %@",dic);
        NSDictionary *dataDic = dic[@"data"];
        NSString *statusStr = dataDic[@"iosStatus"];
        // 从服务器拿到的版本号
        NSString *version = dataDic[@"ios"];
        self.iosUrl = dataDic[@"iosUrl"];
        // 获取当前的版本号
        NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        if ([statusStr isEqualToString:@"0"]) {// 不需要强更
            if (self.backGroundView) {
                [self.backGroundView removeFromSuperview];
            }
        } else {// 需要强制更新
            if ([version isEqualToString:currentVersion]) {// 没有更新
                if (self.backGroundView) {
                    [self.backGroundView removeFromSuperview];
                }
            } else {// 有新版本
                [self updateView];
            }
        }
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
  
}
- (void)updateView{
    if (self.backGroundView) {
        [self.backGroundView removeFromSuperview];
    }
    self.backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.backGroundView.backgroundColor = [UIColor colorWithWhite:0.05 alpha:0.1];
    [[UIApplication sharedApplication].keyWindow addSubview: self.backGroundView];
    
    UIView *whiteMainView = [[UIView alloc] init];
    whiteMainView.backgroundColor = [UIColor whiteColor];
    whiteMainView.layer.cornerRadius = 10;
    whiteMainView.layer.masksToBounds = YES;
    [self.backGroundView addSubview:whiteMainView];
    [whiteMainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(40);
        make.right.offset(-40);
        make.height.offset(140);
        make.centerY.equalTo(self.backGroundView.mas_centerY);
    }];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.text = @"温馨提示";
    titleLabel.textAlignment = YES;
    [whiteMainView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.offset(40);
    }];
    UILabel *contentLabel = [[UILabel alloc] init];
    contentLabel.textColor = [UIColor colorWithHexString:@"#333333"];
    contentLabel.font = [UIFont systemFontOfSize:15];
    contentLabel.text = @"有新的版本，请前往下载！";
    contentLabel.textAlignment = YES;
    [whiteMainView addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(0);
        make.left.right.offset(0);
        make.height.offset(50);
    }];
    UIButton * confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [confirmButton setTitle:@"立即更新" forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmUpdateButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [whiteMainView addSubview:confirmButton];
    
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.bottom.offset(0);
        make.height.offset(40);
    }];
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithHexString:@"#E5E5E6"];
    [whiteMainView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(confirmButton.mas_top).offset(0);
        make.left.right.offset(0);
        make.height.offset(1);
    }];
}
- (void)confirmUpdateButtonClick:(UIButton *)sender{
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.iosUrl]];
}
#pragma mark - ******极光分享******
- (void)jShareConfig{
    //设置应用标识
    JSHARELaunchConfig *config = [[JSHARELaunchConfig alloc] init];
    config.appKey = @"b3b5cfb7e6d36c284f53c15a";
//    config.SinaWeiboAppKey = @"374535501";
//    config.SinaWeiboAppSecret = @"baccd12c166f1df96736b51ffbf600a2";
//    config.SinaRedirectUri = @"https://www.jiguang.cn";
//    config.QQAppId = @"1105864531";
//    config.QQAppKey = @"glFYjkHQGSOCJHMC";
    config.WeChatAppId = @"wx38793707308969c8";
    config.WeChatAppSecret = @"d4fdb996606263a7e12d67c615b9b7f6";
//    config.FacebookAppID = @"1847959632183996";
//    config.FacebookDisplayName = @"JShareDemo";
//    config.TwitterConsumerKey = @"4hCeIip1cpTk9oPYeCbYKhVWi";
//    config.TwitterConsumerSecret = @"DuIontT8KPSmO2Y1oAvby7tpbWHJimuakpbiAUHEKncbffekmC";
    config.JChatProAuth = @"a7e2ce002d1a071a6ca9f37d";
    
    [JSHAREService setupWithConfig:config];
    [JSHAREService setDebug:YES];
}
#pragma mark - 打开别的APP(支付分享等)
// NOTE: 9.0以后使用
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options {
    [JSHAREService handleOpenUrl:url];
    // 其他如支付等SDK的回调
    KMyLog(@"fsasasfa%@",url.host);
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            //code：拿到授权信息，完成业务逻辑
            KMyLog(@"resultDic%@",resultDic);
            if ([[resultDic objectForKey:@"resultStatus"] integerValue] == 9000) {
                [Center postNotificationName:@"shouquanSuccess" object:nil userInfo:resultDic];
            }
        }];
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            
            NSString *statues = resultDic[@"resultStatus"];
            if ([statues isEqualToString:@"9000"]) {
                //支付成功后通知后台
                [Center postNotificationName:@"PaySuccess" object:nil];
                
            }else {
                [Center postNotificationName:@"PayFail" object:nil];
            }
        }];
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
#pragma mark - 微信授权登录 微信支付
-(void)onResp:(BaseResp*)resp {
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        // strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.code == nil) {
            
        } else {// 授权成功
            NSDictionary *diccc = @{@"code":aresp.code};
            [Center postNotificationName:@"wechatshouquanSuccess" object:nil userInfo:diccc];
            //授权成功获取 OpenId
            NSString *code = aresp.code;
            //通过code获取access_token，openid，unionid
            [self getWeiXinOpenId:code];
        }
        
    }
    
    if ([resp isKindOfClass:[PayResp class]]) {
        // strTitle = [NSString stringWithFormat:@"支付结果"];
        // NSLog(@"%@",PayResp.returnKey);
        switch (resp.errCode) {
            case WXSuccess: {
                NSLog(@"支付结果: 成功!");
                [Center postNotificationName:@"PaySuccess" object:nil];
            }
                break;
            case WXErrCodeCommon: {
                //签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                NSLog(@"支付结果: 失败!");
            }
                break;
            case WXErrCodeUserCancel: {
                //用户点击取消并返回
                NSLog(@"用户点击取消并返回");
                [Center postNotificationName:@"PayFail" object:nil];
            }
                break;
            case WXErrCodeSentFail: {
                //发送失败
                NSLog(@"发送失败");
            }
                break;
            case WXErrCodeUnsupport: {
                //微信不支持
                NSLog(@"微信不支持");
            }
                break;
            case WXErrCodeAuthDeny: {
                //授权失败
                NSLog(@"授权失败");
            }
                break;
            default:
                break;
        }
    }
}
- (void)getWeiXinOpenId:(NSString *)code{
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wx38793707308969c8",@"d4fdb996606263a7e12d67c615b9b7f6",code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
            ShowToastWithText(@"微信授权失败");
            return ;
        }
        
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"token、openID字典===%@",dic);
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
        
        //         获取微信用户信息
        [self getUserInfoWithAccessToken:access_token WithOpenid:openid];
        
    });
}
-(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 获取用户信息失败
            if (!data) {
                ShowToastWithText(@"微信授权失败");
                return ;
            }
            
            // 获取用户信息字典
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //用户信息中没有access_token 我将其添加在字典中
            [dic setValue:access_token forKey:@"token"];
            NSLog(@"用户信息字典:===%@",dic);
            
          //微信返回信息后,会跳到登录页面,添加通知进行其他逻辑操作
            [Center postNotificationName:@"weiChatOK" object:nil userInfo:dic];
            
        });
        
    });
    
}
#pragma mark - ******创建主界面******
- (void)setupRootWindow{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    if (USER_ID == nil || [USER_ID isEqualToString:@""]) {
        //验证码登录界面
        CodeLoginController *vc = [[CodeLoginController alloc]init];
        BaseNavViewController *nav = [[BaseNavViewController alloc]initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        self.window.rootViewController = nav;
        
    }  else {
        //创建Tabbar
        TabBarViewController *tabbar = [[TabBarViewController alloc]init];
        self.window.rootViewController = tabbar;
    
    }
    [self.window makeKeyAndVisible];
    //存储udid
    NSString *udid =[USER_DEFAULT objectForKey:@"udid"];
    if (strIsEmpty(udid)) {
        udid =    [self uuid];
        [USER_DEFAULT setObject:udid forKey:@"udid"];
    }
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [Center postNotificationName:@"applicationWillEnterForeground" object:nil userInfo:nil];
    
}
//获得UUID
- (NSString*)uuid {
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString *result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    return result;
}
@end
